package com.example.ui_view.nework;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import com.example.ui_view.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetworkImageActivity extends AppCompatActivity {
    ImageView iv_image;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_image);
        iv_image = findViewById(R.id.iv_image);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x1100){
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv_image.setImageBitmap(bitmap);
                }
            }
        };
    }

    public void start(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                HttpURLConnection connection = null;
                InputStream is = null;
                Bitmap bitmap = null;
                try {
                    url= new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1608011852801&di=5ac0bab1806ff76596a2a8d9b8284659&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F71%2F56%2F16300000988660128426569668958.jpg");
                    connection = (HttpURLConnection) url.openConnection();
                    is = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    Message message = new Message();
                    message.what = 0x1100;
                    message.obj = bitmap;
                    handler.sendMessage(message);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
